package com.mano233.server.config.json;

import com.mano233.server.config.json.annotation.JsonCustomFilter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义HandlerMethodReturnValueHandler
 * 用于处理自定义的@JsonFilter注解，来过滤json属性
 *
 * @author mano233
 * @see JsonReturnHandler
 * @see JsonCustomFilter
 */
@Configuration
public class ReturnJsonCustomConfig implements InitializingBean {
    private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Autowired
    public ReturnJsonCustomConfig(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
    }

    @Override
    public void afterPropertiesSet() {
        List<HandlerMethodReturnValueHandler> unmodifiableList = requestMappingHandlerAdapter.getReturnValueHandlers();
        List<HandlerMethodReturnValueHandler> list = null;
        if (unmodifiableList != null) {
            list = new ArrayList<>(unmodifiableList.size());
            for (HandlerMethodReturnValueHandler returnValueHandler : unmodifiableList) {
                if (returnValueHandler instanceof RequestResponseBodyMethodProcessor) {
                    list.add(new JsonReturnHandler(returnValueHandler));
                } else {
                    list.add(returnValueHandler);
                }
            }
        }
        requestMappingHandlerAdapter.setReturnValueHandlers(list);
    }
}
